// const modelBusiness = require('camraBnessgai.js')
const modelTest = require('cameraBusiness-test.js')
var app = getApp()
const canvasId = 'canvas1';

const modelUrl = 'https://www.juquduo.com/static/models/Dying.glb';
var isDeviceMotion = false, isAndroid = false, redboll = 1;
var attackimg1 = 'https://www.juquduo.com//static/images/qqyp.gif';
var attackimg2 = 'https://www.juquduo.com//static/images/pg.gif';
var attackimg3 = 'https://www.juquduo.com//static/images/bj.gif';

var left='', sitetype, fangyu=0, sdsdid, top='', j = 1, speed = 1, speedgr = 1;
// 提交的位置信息
var xsite,ysite
// 用于小球方向控制;
var wz = 1,wzgr = 1,poid,name1='',name2='',name3='',monsmsg,acsite = 'gbsz',mode

Page({
  data: {
    Avatar:'',wjdiaoxue:'',monsdiaoxue:'',showwjdiaoxue:'',showmonsdiaoxue:'',
    monstishi:false,showtishimons:true, show:true,
    showwithmons:true,wjwin:false,
    disab:'',  showaaa:false,  devicePosition: 'back',
    redspeed:'', greenspeed:'',roundskip:'',
    img:false,timer:'',timergr:'',timeshow:'',
    left:'1px', top:'1px',roundmon:false,roundwj:true,
    bloodstate:100,attackimg:'',
    bloodstate1:'100',  speed:'',atked:true,
    openid:'',  width:'',height:'',  mondetail:[],  xue:false
  },
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    setTimeout(function () {
    // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1500);
  },
  onLoad(options) {
    this.red()
    var headimg = wx.getStorageSync('headimg')
    // console.log('头像信息',headimg)
    this.setData({Avatar:headimg.avatarUrl})
    console.log('参数acsite',acsite)
    // var name1,name2,name3
    wx.request({
      url: 'https://www.juquduo.com/test/model',
      data:{model:acsite},
      success(res){
        // console.log(res.data)
        monsmsg = res.data
        name1 = monsmsg.ModelName
        name2 = monsmsg.MeshName
        name3 = monsmsg.AnimateName
        // console.log(name1,name2,name3)
      },
      complete(){
        name1 = 'act'
        // name2 = 'Guard02'
        name2 = 'mixamorig_Hips'
        name3 = 'batk'
        console.log('三个参数',name1,name2,name3)
        // 开始加载动画
        _that._init(j)
      }
    })
    if(acsite=='gbsz'){
      acsite = 'cygy'
    }else if(acsite=='cygy'){
      acsite = 'gbsz'
    }
  //自己血量的倒计时进度条
    var _that = this;
    let timer;
    poid = options.pid
    sdsdid = options.acid
    sitetype = options.sitetype
    mode = options.mode
    if(mode==undefined){mode=2}
    console.log('怪兽关卡1的序号pid',poid)
    //获取openid,没有则给一个假的
    var openid = wx.getStorageSync('openid')
    if(openid==''||openid==undefined){
      openid = openid
    }
    _that.setData({openid:openid})
    //获取怪物信息,没有则给一个假的
    var mons = wx.getStorageSync('pointmsg')
    console.log('怪物信息',mons)
    if(mons==''||mons==undefined){
      mons= ({'PointId':6,'MonDiff':2})
    }
    mons= ({'PointId':6,'MonDiff':1})
    this.setData({mondetail:mons})

    //获取设备信息
    const res = wx.getSystemInfoSync();
    console.log(res.system);
    if (res.system.indexOf('Android') !== -1) {
      isAndroid = true;
    }
    console.log('怪物等级',_that.data.mondetail.MonDiff)
  },
  onShow(){
      // 开始方向检测
      // modelTest.startDeviceMotion(isAndroid)
  },
  onUnload() {
    isDeviceMotion = false;
    modelTest.stopanimate();
    modelTest.stopDeviceMotion();
    wx.offDeviceMotionChange();
    wx.stopDeviceMotionListening({
      success: (res) => {},
    })
    clearInterval(this.timer)
    clearInterval(this.timergr)
    clearInterval(this.timeshow)
    clearTimeout(this.roundskip)
  },
  onHide(){
    var that= this
    wx.offDeviceMotionChange();
    wx.stopDeviceMotionListening({
      success: (res) => {},
    })
    clearInterval(that.timer)
    clearInterval(that.timergr)
    clearInterval(that.timeshow)
    clearTimeout(that.roundskip)
  },
  // 开始加载模型时，显示提示
  startloadmodel(){
    var that= this
    //显示提示文字、显示控制板，
    this.setData({monstishi:true,showtishimons:false})
    // console.log(this.data)
  },
  // 模型架加载完之后，隐藏提示文字
  modelloaded(){
    var that= this
    this.roundmons()
    //隐藏提示文字
    that.setData({monstishi:false,showwithmons:true,xue:true})
    console.log(modelTest.last_device)
    
    wx.startDeviceMotionListening({
      interval: 'normal',
    })
    var timeshow =that.timeshow =  setInterval(function(){
      var keyida = modelTest.duizhun(isAndroid)
      console.log(keyida)
      if(keyida=='2'){
        that.setData({show:true})
      }else{
        that.setData({show:false})
      }
    },200)
  },
  //播放红球和蓝球的动画
  red(){
    var _that = this
    
    var timer =_that.timer  = setInterval(function(){
        // console.log('红球动')
        //如果小于180，球往右移动，每次9像素,wz=1,向右
        if(speed<=181&&wz==1){speed+=15}
        //如果大于180，切换移动方向，向左移动
        if(speed>181){wz=2}
        //向左移动，如果大于1，就每次减9像素
        if(speed>=1&&wz==2){speed-=15}
        //如果低于1，切换移动方向，向右移动
        if(speed<=1){wz=1}
        //提交到页面显示，用于小球移动
        _that.setData({speed:speed})
        if (redboll == 2) {
          //用于提交服务器
          clearInterval(timer)
          _that.setData({redspeed:speed})
          // console.log('左边距离'+speed)
          var timergr =_that.timergr =  setInterval(function(){
            // console.log('蓝球动')
            //如果大于0，球往下移动，每次4像素
            if(speedgr>0&&wzgr==1){speedgr+=7}
            //如果大于90，切换移动方向，向上移动
            if(speedgr>=91){wzgr=2}
            //如果小于94，球往上移动，每次4像素
            if(speedgr<=100&&wzgr==2){speedgr-=7}
            //如果小于1，切换移动方向，向下移动
            if(speedgr<=1){wzgr=1}
          //提交到页面显示，用于小球移动
            _that.setData({speedgr:speedgr})
            if (redboll == 1) {
              //用于提交服务器
              clearInterval(timergr)
              _that.setData({greenspeed:speedgr})
              // console.log('顶部距离'+speedgr)
            }
          },500)
        }
      },500)
  },
  // 每次点击都调用
  changebtn(){
    var that = this
    that.setData({roundwj:true})
    //切换小球动画，redball为1，则红球动
    if(redboll==1){
      redboll = 2
      this.red()
      xsite = Math.abs(90-speed)
    }else{
      redboll = 1
      this.red()
      ysite = Math.abs(speedgr-45)
      // console.log(xsite,ysite)
      wx.request({
        url: 'https://www.juquduo.com/juquduo/gaming/monster_details',
        data:{
          activityId:sdsdid,
          // activityId:124,
          pointId:this.data.mondetail.PointId,
          openid:that.data.openid,
          mon_diff:this.data.mondetail.MonDiff,
          xTotal:180/2,
          yTotal:90/2,
          xHurt:xsite,
          yHurt:ysite
        },
        success(res){
          // 本次伤害值除以怪物难度，怪物难度乘一百是怪物血量
          fangyu = res.data.MyArmorBonus
          if(res.data.AvoidHurt<=5){
            that.setData({attackimg:attackimg1})
          }else if(res.data.AvoidHurt<=10){
            that.setData({attackimg:attackimg2})
          }else if(res.data.AvoidHurt<=25){
            that.setData({attackimg:attackimg3})
          }
          var hurtpersent = res.data.AvoidHurt/1
          that.caozuo1(hurtpersent)     //修改进度条数值，减去本次的百分比
          // console.log(hurtpersent)   //本次伤害的百分比
          // console.log(res.data)  //本次伤害信息
          that.setData({showwithmons:false})
          setTimeout(
            function () {
              // console.log(333)
              that.setData({
                showwithmons:true
              })
            }, 4000)
        }
      })
    }
  },
  //点击第二次后调用，
  caozuo1(hurtblood){
    var that = this
    if(!hurtblood){hurtblood = 10}
    var xue2 = '-'+hurtblood+' '
    console.log(xue2,hurtblood)
    that.setData({monsdiaoxue: xue2,showmonsdiaoxue:false})
    setTimeout(function () {  
      that.setData({showmonsdiaoxue:true})
    }, 1000)
    clearTimeout(that.roundskip)
    // 点第二次之后播放 被击退动画
    modelTest.start2(1)
    that.roundmons()
    var that = this
    //修改进度条，
    var blood = this.data.bloodstate
    // console.log(blood)
    blood = blood-hurtblood
    // console.log(blood)
    this.setData({bloodstate:blood})
    // blood是怪物血量，进度条为0，跳转页面
    if(blood<=0){
      clearInterval(that.timer)
      clearInterval(that.timergr)
      clearInterval(that.timeshow)
      clearTimeout(that.roundskip)
      wx.offDeviceMotionChange();
      wx.stopDeviceMotionListening({
        success: (res) => {},
      })
      // 用于取消下面定时器的代码，定时器已经开始，然后if 不成立的话不显示模态框
      this.data.wjwin = true
      wx.redirectTo({
        url: '../dgameques/dgameques?state=1&pid='+poid+'&sitetype='+sitetype+'&mode='+mode,
      })
    }
    //图片位置
    left= Math.floor(Math.random()*30+0)+'px'
    top=Math.floor(Math.random()*30+0)+'px'

    //显示图片
    var that = this;
    that.setData({ 
      img:true,
      left:left,
      top:top
    })
    //将计时器赋值给setInter。让图显示消失的秒数
    setTimeout(function () {
        // console.log(333)
        that.setData({
          img:false
        })
      }, 1000) 
  },
  // 怪兽打人回合
  roundmons(){
    var that = this
    var bloodme
    // 前面是玩家攻击回合，怪兽打完是玩家回合,2秒之后播放攻击动画
    setTimeout(function () {
      modelTest.start2(0)
      that.setData({roundmon:true,roundwj:true})
      // 攻击3秒后开始玩家回合，回合提示显示3秒，或玩家点击后消失
      setTimeout(function () {
        that.setData({roundmon:false,roundwj:false})
        setTimeout(function () {
          that.setData({roundwj:true})
        }, 3000)
      }, 3000)
    }, 2000)

    // 1秒之后(模拟怪兽打到人的时间)，掉血，要有掉血的数量
    setTimeout(function () {  
      if(fangyu == undefined){fangyu = 0}
      var diaoxue = 12*(1-(100+ fangyu )/500)
      // console.log(diaoxue)
      bloodme = that.data.bloodstate1-diaoxue
      var wjdiaoxue = parseInt(diaoxue)
      var xue3 = '-'+wjdiaoxue+' '
      console.log(xue3,wjdiaoxue,diaoxue,fangyu)
      that.setData({bloodstate1:bloodme,atked:false,wjdiaoxue:xue3,showwjdiaoxue:false})
      // 红色背景显示0.3秒
      setTimeout(function () {  
        that.setData({atked:true})
        setTimeout(function () {  
          that.setData({showwjdiaoxue:true})
        }, 700)
      }, 300)
      if(bloodme<=0&&that.data.wjwin==false){
        clearTimeout(that.roundskip)
        // 用于控制模态框只显示一次
        that.data.wjwin = true
        wx.showModal({
          title:'挑战失败，是否重试？',
          confirmText:'重试',
          cancelText:'退出',
          success(res){
            clearTimeout(that.roundskip)
            if (res.confirm) {//重试，初始化
              that.setData({bloodstate1:100,bloodstate:100})
              that.data.wjwin = false
              that.roundmons()
            }else{//退出
              wx.redirectTo({
                url: '../dgameques/dgameques?state=0&pid='+poid+'&sitetype='+sitetype+'&mode='+mode,
              })
              clearInterval(that.timer)
              clearInterval(that.timergr)
              clearInterval(that.timeshow)
              wx.offDeviceMotionChange();
              wx.stopDeviceMotionListening({
                success: (res) => {},
              })}}})}
    }, 3000)

    // 调用则开启10秒定时器，到时间则开始怪兽回合,人点按钮第一次之后不重启定时器，定时器不改变，"怪兽回合之后开始定时器"
    // 刚加载就要开始这个定时器，这个定时器要13秒运行一次，递归
    that.roundskip = setTimeout(function () { 
      // console.log('攻击回合结束，开始怪兽回合')
      that.roundmons()
    }, 13000) 
  },
  // 跳过回合的定时器，10秒之后，到怪兽回合，停掉就不会递归
  // 调用则开启10秒定时器，到时间则开始怪兽回合,人点按钮之后重启定时器，怪兽回合之后开始定时器 用于开启定时器，放到data里面可以关闭定时器
  skipround(){
    var that = this
    
  },
  enen:function(){
    var that = this
      clearInterval(that.timer)
      clearInterval(that.timergr)
      clearInterval(that.timeshow)
      clearTimeout(that.roundskip)
      wx.offDeviceMotionChange();
      wx.stopDeviceMotionListening({
        success: (res) => {},
      })
    wx.redirectTo({
      url: '../getpoi/getpoi',
      // url: '../dgameques/dgameques?state=1&pid='+poid+'&sitetype='+sitetype,
    })
  },
  _init(i){
    var that=this;
    modelTest.initThree(canvasId,name1,name2,name3,
      function (THREE) {
        modelTest.initScene(false);
        console.log('monsmsg发送的参数',name1,name2,name3)
      }),
      // 开始方向检测
    modelTest.startDeviceMotion(isAndroid)
    // console.log(modelTest.startDeviceMotion())
    isDeviceMotion = true
  },
  bindtouchstart_callback(event) {
    // modelTest.onTouchstart(event);
  },
  bindtouchmove_callback(event) {
    modelTest.onTouchmove(event);
  },
  //另一个文件里的代码，检测镜头方向、添加交互'
  toggleDeviceMotion() {
    if (isDeviceMotion) {
      modelTest.stopDeviceMotion();
    } else {
      modelTest.startDeviceMotion(isAndroid);
    }
    isDeviceMotion = !isDeviceMotion;
  }
});